
from time import sleep
from pyx_package.script import BaseBehavior
from pyx_package.ps_paramete import PsParameter
PYX_MODULE_NAME = "列表迭代器"

class ScriptBehavior(BaseBehavior):

    def __init__(self) -> None:
        super().__init__()
        
        self.SetExeMode("iter")
        
        self.InitInputParam()
        
        self.InitOutputParam()
        
    def InitInputParam(self):
    
        self.list = self.CreateParam(
            "list", "迭代列表", PsParameter.Input, list)
            
        #间隔时间
        self.interval_time = self.CreateParam(
            "interval_times", "迭代间隔时间", PsParameter.Input, float)
        self.interval_time.value = 0.0
            
        #初始化列表
        self.list.value = []
        
    def InitOutputParam(self):
        
        #下发元素参数
        self.issus_element = self.CreateParam(
            "element", "列表元素", PsParameter.Output, any)
            
        #当前下发的索引
        self.issus_times = self.CreateParam(
            "issus_times", "列表元素", PsParameter.Output, int)
        self.issus_times.value = 0
        
        self._iter_index = 0
        
    def FirstStep(self):
        '''
            第一次执行解析元素类型
        '''
        self.Debug("列表元素数量:" + str(len(self.list.value)), "infomation")
        if len(self.list.value) == 0:
            return 

        self.issus_element.type = type(self.list.value[0])
        self._iter_index = 0
        
    def DoStep(self):
    
        if len(self.list.value) == 0:
            return 
        
        #停顿间隔时间
        sleep(self.interval_time.value)
        
        #取出一个元素，设置到输出参数中
        self.issus_element.value = self.list.value[self._iter_index]
        
        #设置当前下发的索引
        self.issus_times.value = self._iter_index
        
        #索引+
        self._iter_index += 1
        
        #如果是最后一个元素，就结束迭代
        self.Debug("列表元素数量:" + str(len(self.list.value)) + "当前索引 ： " + str(self._iter_index), "infomation")
        if len(self.list.value) == self._iter_index:
            self.Debug("结束l lllll ")
            self.Finish()
            